/**
 * 
 */
package com.effectivsocial.controller;

import java.util.Locale;

import javax.inject.Inject;
import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.effectivsocial.domain.Company;
import com.effectivsocial.domain.User;
import com.effectivsocial.service.api.EmailService;
import com.effectivsocial.service.api.UserService;

/**
 * @author Dhrubo
 *
 */
@Controller
@Slf4j
public class RegistrationController {
	
	@Inject
	private UserService userService;
	
	@Inject
	private EmailService emailService;

	@RequestMapping(value="/guest/subscribe") 
	public String showForm(Model model){
				
		log.info("----------------------Join us ---------------------------");
		
		User user = new User();
		user.setCompany(new Company());
		
		model.addAttribute(user);
		
		return "subscribe";
	}
	
	
		
	@RequestMapping(value={"/registeruser", "/guest/registeruser"}, method=RequestMethod.POST)
	public String registerUser(@Valid User user, BindingResult result, Locale locale){
		log.info("COmpany for saving = {}", user.getCompany().getName());
		log.info("user for saving = {}", user.getEmail());
		log.info("user for saving = {}", user.getPassword());
		
		
		log.info("Binding result = {}", result.getAllErrors());
		
		//TODO --- REMOVE THIS CHECK
		if (!result.hasErrors()) {
			//leadService.save(lead);
			
			userService.save(user, user.getCompany());
			
			
			log.info("##### sending email");
			
			emailService.sendOnRegister(user, locale);
		} 
		
		return "subscribe";
	}
	
	@RequestMapping(value="/guest/activate") 
	public String activate(Model model, @RequestParam("email") String email) {
		userService.unlock(email);
		model.addAttribute("info", "successActivation");
		return "signin";
	}
	
}
